package com.lw.leetcode.arr.b;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 1733. 需要教语言的最少人数
 *
 * @author liw
 * @version 1.0
 * @date 2022/11/3 14:11
 */
public class MinimumTeachings {

    public static void main(String[] args) {
        MinimumTeachings test = new MinimumTeachings();

        // 1
        int n = 2;
        int[][] languages = {{1}, {2}, {1, 2}};
        int[][] friendships = {{1, 2}, {1, 3}, {2, 3}};

        // 2
//        int n = 3;
//        int[][] languages = {{2}, {1, 3}, {1, 2}, {3}};
//        int[][] friendships = {{1, 4}, {1, 2}, {3, 4}, {2, 3}};

        int i = test.minimumTeachings(n, languages, friendships);
        System.out.println(i);
    }

    public int minimumTeachings(int n, int[][] languages, int[][] friendships) {
        int m = languages.length;
        int[][] arr = new int[m][n];
        for (int i = 0; i < m; i++) {
            int[] language = languages[i];
            int[] items = arr[i];
            for (int v : language) {
                items[v - 1] = 1;
            }
        }
        List<Integer> list = new ArrayList<>();
        int length = friendships.length;
        for (int i = 0; i < length; i++) {
            int[] friendship = friendships[i];
            int a = friendship[0] - 1;
            int b = friendship[1] - 1;
            if (languages[a].length + languages[b].length > n) {
                continue;
            }
            int[] language = languages[a];
            int[] itmes = arr[b];
            boolean flag = true;
            for (int j : language) {
                if (itmes[j - 1] == 1) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                list.add(i);
            }
        }
        if (list.isEmpty()) {
            return 0;
        }
        int max = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            int c = 0;
            for (int index : list) {
                int[] friendship = friendships[index];
                int a = friendship[0] - 1;
                int b = friendship[1] - 1;
                if (arr[a][i] == 0) {
                    arr[a][i] = 1;
                    c++;
                }
                if (arr[b][i] == 0) {
                    arr[b][i] = 1;
                    c++;
                }
            }
            max = Math.min(max, c);
        }
        return max;
    }

}
